<?php

declare (strict_types=1);

namespace app\api\middleware;

use app\api\service\ApiTokenService;
use Closure;
use think\response\Json;
use tmcore\traits\JsonTrait;

/**
 * 登录中间件
 */
class LoginMiddleware
{
    use JsonTrait;

    /**
     * 登录验证
     * @param $request
     * @param Closure $next
     * @return mixed|Json
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('authorization');
        if (empty($token)) return self::error('请求参数缺token', 10006);

        $userInfo = ApiTokenService::getUserInfo($token);
        if (empty($userInfo)) {
            return self::error(ApiTokenService::getError('登录超时，请重新登录'), 100007);
        }

        // request赋值用户信息
        $request->userInfo = $userInfo;
        $request->userId = $userInfo['id'] ?? 0;

        return $next($request);
    }

}